<%@ page language="java" contentType="text/html; charset=UTF-8"	 pageEncoding="UTF-8"%>
<%@ include file="../include/laypublic.jsp"%>
<!DOCTYPE html>
<html>
<head>
  <title>概算分劈</title>
</head>
<script type="text/html" id="layui-row"  >
    <div class="layui-row" id="{0}" >
        <div class="contract-box" >
            <div class="contract-money">
                <table class="layui-table">
                    <colgroup>
                        <col width="200">
                        <col width="400">
                        <col width="400">
                        <col width="400">                       
                    </colgroup>
					<thead>
                    <tr>
                        <td class=tg-c>子项名称<input type="hidden" value="{1}"  name="subNames"  class="subNames" /></td>
                        <td class=tg-c >{1}</td>                        
                        <td></td>
                        <td></td>                       
                    </tr>
                    </thead>
                    <tbody>
                    <tr>
                        <th>费用类型</th>
                        <th>对外下浮前金额(元)</th>
                        <th>对外下浮率(%)</th>
                        <th>对外下浮后金额(元)</th>
                    </tr>
                   </tbody>
                    <tbody >
                    <tr id="{0}Row-1" level=1 >
                        <td  class=tg-c  ><input type="hidden" value="1" name="orderIdxs" /><input type="hidden" value="{0}" name="contractSubIds" />
                        <b>建安工程费</b><input type="hidden" value="1" name="feeTypes" /><input type="hidden" value="{1}"  name="itemNameSub"  class="itemNameSub" /><input type="hidden" value="-1" name="feeSmallTypes" /><input type="hidden" value="建安工程费" name="typeNames" class="typeNames" /></td>
                        <td><input style="text-align:center;border:0px;" type="text" name="outPreDownAmounts" readonly  autocomplete="off" class="layui-input projectamountbefore" /></td>
  						<td><input style="text-align:center;border:0px;" type="text" name="outPreDownRates" readonly autocomplete="off" class="layui-input outdiscount" /></td>
                        <td><input style="text-align:center;border:0px;" type="text" name="outAfterDownAmounts" readonly  autocomplete="off" class="layui-input inamountafter" /></td>
                    </tr>
                    <tr id="sub{0}Row-1.1"  level=2 >
                        <td  class=tg-c  ><input type="hidden" value="1.1" name="orderIdxs" /><input type="hidden" value="{0}" name="contractSubIds" />
                        <label>土建</label><input type="hidden" value="1" name="feeTypes" /><input type="hidden" value="{1}" name="itemNameSub"  class="itemNameSub" /><input type="hidden" value="1.1" name="feeSmallTypes" /><input type="hidden" value="土建" name="typeNames"  class="typeNames"  /></td>
                   		<td><input style="text-align:center;border:0px;" type="text" name="outPreDownAmounts" readonly  autocomplete="off" class="layui-input projectamountbefore" /></td>
  						<td><input style="text-align:center;border:0px;" type="text" name="outPreDownRates" readonly autocomplete="off" class="layui-input outdiscount" /></td>
                        <td><input style="text-align:center;border:0px;" type="text" name="outAfterDownAmounts" readonly  autocomplete="off" class="layui-input inamountafter"/></td>
                    </tr>
                    <tr id="sub{0}Row-1.2"  level=2>
                        <td  class=tg-c><input type="hidden" value="1.2" name="orderIdxs" /><input type="hidden" value="{0}" name="contractSubIds" />
                        <label>安装</label><input type="hidden" value="1" name="feeTypes" /><input type="hidden" value="{1}" name="itemNameSub" class="itemNameSub" /><input type="hidden" value="1.2" name="feeSmallTypes" /><input type="hidden" value="安装" name="typeNames"  class="typeNames" /></td>
                   		<td><input style="text-align:center;border:0px;" type="text" name="outPreDownAmounts" readonly autocomplete="off" class="layui-input projectamountbefore" /></td>
  						<td><input style="text-align:center;border:0px;" type="text" name="outPreDownRates" readonly autocomplete="off" class="layui-input outdiscount" /></td>
                        <td><input style="text-align:center;border:0px;" type="text" name="outAfterDownAmounts" readonly  autocomplete="off" class="layui-input inamountafter" /></td>
                    </tr>                   
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</script>

<style>
	.list-title{
		display:block;
		width:270px;
		text-align:right;
		left:5px;
		font-size:.89em;
	}
	
	.pos-r{
		position: relative;
	}
	.pos-a{
		position: absolute;
	}
	
	.margin-bot10 {
		margin-bottom: 10px;
	}
	
	.margin-lt10 {
		margin-left: 10px;
	}
	
	.layui-row+.layui-row {
		margin-top: 10px;
	}
	
	.tg-l {
		text-align: left;
	}
	
	.tg-c {
		text-align: center;
	}
	
	.tg-r {
		text-align: right;
	}
	
	.contract-list {
		margin-top: 20px;
	}
	
	.contract-box {
		width: 100%;
		min-height: 100px;
	}
	
	.contract-money {
		width: 94%;
		margin: 0px auto;
	}
	
	.contract-money .layui-table {
		margin: 0;
	}
	
	.contract-money th {
		text-align: center;
		height: 38px;
	}
	
	.contract-money .label {
		display: block;
		width: 45px !important;
		margin-left: 15px;
	}
	
	.fieldset {
		margin-top: 5px;
		margin-bottom: 0px
	}
	
	.layui-legend {
		background-color: #5fb878;
		font-size: 15px !important;
		width: 140px;
	}
	
	.layui-form-item {
		margin-bottom: 5px;
		clear: both;
		*zoom: 1;
	}
	
	.layui-form-label {
		width: 160px;
	}
</style>
<body>
	<div class="layui-fluid">
		<div class="layui-card">
			<div style="padding-top: 15px;">&nbsp;</div>
			<form class="layui-form" id="addInfo_form" lay-filter="addInfo_form">
				<div class="layui-tab layui-tab-brief" >
					<div class="layui-tab-content">
						<div class="layui-tab-item layui-show">
							
							<fieldset class="layui-elem-field layui-field-title fieldset" id="baseInfo" >
								<legend class="layui-btn layui-legend"
									style="text-align: left; cursor: default;" >项目基础信息 ></legend>
								<div class="layui-form-item">
									<div class="layui-inline">
										<label class="layui-form-label">申请公司</label>
										<div class="layui-input-inline">
											<input type="hidden" name="hrOrgid" value="${bindOrgId}">
											<input type="text" value="${bindOrgName}"
												style="border: 0px;" readonly="readonly" class="layui-input">
										</div>
									</div>
									<div class="layui-inline">
										<label class="layui-form-label">申请部门</label>
										<div class="layui-input-inline">
											<input type="hidden" name="hrDeptid" value="${bindDeptId}">
											<input type="text" value="${bindDeptName}"
												style="border: 0px;" readonly="readonly" class="layui-input">
										</div>
									</div>
									<div class="layui-inline">
										<label class="layui-form-label">申请人</label>
										<div class="layui-input-inline">
											<input type="hidden" name="hrStaffApplyid"
												value="${SESSION_KEY_USER_DETAIL.hrStaffId }"> <input
												type="text" name="staffname" value="${SESSION_KEY_USER_DETAIL.realName }"
												readonly="readonly" style="border: 0px" autocomplete="off"
												class="layui-input">
										</div>
									</div>
								</div>
								<div class="layui-form-item">
									<div class="layui-inline">
										<label class="layui-form-label">项目名称</label>
										<div class="layui-input-inline">
											<input type="hidden" id="id_proCode" name="proCode" value="">
											<input type="text" name="proNames" value="${budgetBatchVo.proName}" 
												style="border:0px;width:265px" readonly="readonly" class="layui-input">
											<input type="hidden" name="proCodeAndCodes" value="${budgetBatchVo.proCode}_${budgetBatchVo.id}_${budgetBatchVo.proName}"
												style="border:0px;width:220px" readonly="readonly" class="layui-input">
										</div>
									</div>
									<div class="layui-inline">
										<label class="layui-form-label">实施机构</label>
										<div class="layui-input-inline">
											<input type="text" value="${budgetBatchVo.carryOrg}" id="id_ImplementingBody" name="carryOrg" style="border: 0px;"
												readonly="readonly" class="layui-input">
										</div>
									</div>
									<div class="layui-inline">
										<label class="layui-form-label">区域公司</label>
										<div class="layui-input-inline">
											<input type="text" value="${budgetBatchVo.orgAreaName}" id ="query-input-hrOrgAreName" style="border: 0px;width:220px" 
										 		 readonly="readonly" class="layui-input">
											<input type="hidden" name="hrOrgAreaId" value="${budgetBatchVo.hrOrgAreaId}" id ="query-input-hrOrgAreName" style="border: 0px;width:220px" 
										 		 readonly="readonly" class="layui-input">
										</div>
									</div>																
								</div>
								<div class="layui-form-item">									
									<div class="layui-inline">
										<label class="layui-form-label">项目负责人</label>
										<div class="layui-input-inline">
											<input type="text" value="${budgetBatchVo.proLeader}" id="id_projectLeader" name="proLeader" style="border: 0px;"
												readonly="readonly" maxlength="10" lay-verify="required|COC"
												class="layui-input">
										</div>
									</div>
									<div class="layui-inline">
										<label class="layui-form-label">项目地址</label>
										<div class="layui-input-inline">
											<input type="hidden" id="sgCityId" name="sgCityId" value="${budgetBatchVo.sgCityId}">
											<input type="text" id="id_projectAddress" name="projectAddress" value="${budgetBatchVo.sgCityName}"
												style="border: 0px;" readonly="readonly" class="layui-input">
										</div>
									</div>
								</div>												
							</fieldset>						
							<fieldset class="layui-elem-field layui-field-title fieldset" id="projectSubDetail" >
								<legend class="layui-btn layui-legend" style="text-align: left; cursor: default;" >项目子项明细 ></legend>
								<div class="contract-list" >																	
									<div class="contract-box margin-bot10" >
	            						<div class="contract-money">
	                						<table class="layui-table">
							                    <colgroup>
							                        <col width="200">
							                        <col width="400">
							                        <col width="400">
							                        <col width="400">	        
							                    </colgroup>
							                    <c:forEach items="${budgetBatchVo.budgetBatchSubVos}" var="sub" varStatus="status">
												<thead>
													<tr>
								                        <td class=tg-c>子项名称</td>
								                        <td class="tg-c">${sub.subName }
								                        	<input type="hidden" name="subNames" value="${sub.subName }"/>
								                        </td>                        
								                        <td></td>
								                        <td></td>								                        
								                    </tr>
												</thead>
												<tbody>
													<tr>									
														<th>费用类型</th>
														<th>对外下浮前金额(元)</th>
														<th>对外下浮率(%)</th>
														<th>对外下浮后金额(元)</th>
													</tr>
								                </tbody>
								                <tbody>
							                    <c:forEach items="${sub.budgetBatchDetails }" var="detail" varStatus="subStatus">					                    					         
								                    <tr>
								                        <td class=tg-c>
								                        	<c:if test="${subStatus.count == 1 }">
								                        		<b>${detail.typeName }</b>
								                        	</c:if>
							                        		<c:if test="${subStatus.count > 1 }">${detail.typeName }</c:if>
							                        		<input type="hidden" name="typeNames" value="${detail.typeName }"/>
							                        		<c:if test="${detail.feeSmallType == -1 }">
							                        			<input type="hidden" name="feeSmallTypes" value="${detail.feeSmallType }"/>
							                        		</c:if>
							                        		<c:if test="${detail.feeSmallType != -1 }">
							                        			<input type="hidden" name="feeSmallTypes" value="${detail.orderIdx}"/>
							                        		</c:if>
							                        		<input type="hidden" name="orderIdxs" value="${detail.orderIdx }"/>
							                        		<input type="hidden" name="itemNameSub" value="${sub.subName }"/>
								                        </td>
								                        <td><input type="text" name="outPreDownAmounts" value="${detail.outPreDownAmount}" readonly style="border:0px;text-align: center;" class="layui-input" /></td>
								  						<td><input type="text" name="outPreDownRates" value="${detail.outPreDownRate}" readonly style="border:0px;text-align: center;" class="layui-input" /></td>
								                        <td><input type="text" name="outAfterDownAmounts" value="${detail.outAfterDownAmount}" readonly style="border:0px;text-align: center;" class="layui-input" /></td>
								                    </tr>					                     
							                    </c:forEach>                  
				                    			</tbody>
					                		</c:forEach>
							                </table>
	                    				</div>
                    				</div> 
								</div>								
							</fieldset>		
							<fieldset class="layui-elem-field layui-field-title fieldset" id="budgetBatchList" >
								<legend class="layui-btn layui-legend" style="text-align: left; cursor: default;" >概算清单 ></legend>	
								<div class="contract-box" style="margin-top:20px;" id="batchList">
            						<div class="contract-money">
                						<table class="layui-table">
						                    <colgroup>
						                        <col width="90"  >
						                        <col width="200" >
						                        <col width="200" >
						                        <col width="200" >
						                        <col width="200" >
						                        <col width="200" >
						                        <col width="200" >
						                        <col width="220" >
						                    </colgroup>
											<thead>
												<tr>
													<th>序号</th>
													<th>子项</th>
													<th>细分子项</th>
													<th>合同金额(元)</th>
													<th>概算金额(元)</th>
													<th>增减金额(元)</th>
													<th>说明</th>
													<th></th>
												</tr>
											</thead>
											<tbody>
												<c:forEach items="${budgetBatchVo.budgetBatchLists}" var="list" varStatus="status">
												<tr id="batchRow${status.count }">
							                    	<td class="tg-c"><input type="text" name="batchList[0].showIdx" value="${list.showIdx }" style="border: 0px;width:50px" readonly="readonly" class="layui-input"></td>
							                    	<td id="select_subname">
							                    		<select id="add_select_subName" name="batchList[0].listSubName" 
							                    			lay-verify="required" lay-filter="add_select_subName">
							                    			<option value="">请选择</option>
											      				<c:if test="${not empty proContractSubs }">
											              			<c:forEach items="${proContractSubs}" var="coops">
											              				<option value="${coops.subName }" <c:if test="${list.listSubName == coops.subName}">selected</c:if>>${coops.subName }</option>
												            		</c:forEach>
											              		</c:if>
							                    		</select>
							                    	</td>
							                    	<td><input type="text" value="${list.subDivideName }" name="batchList[0].subDivideName" maxlength="50" lay-verify="required" autocomplete="off" class="layui-input"></td>
							                    	<td><input type="text" value="${list.cotAmount }" name="batchList[0].cotAmount" onblur="calcSumAmount(this);arabiaToCN(this,1);" maxlength="13" lay-verify="required|floatNumber" autocomplete="off" class="layui-input"></td>
							                    	<td><input type="text" value="${list.budgetAmount }" name="batchList[0].budgetAmount" onblur="calcSumAmount(this);arabiaToCN(this,1);" maxlength="13" lay-verify="required|floatAmount" autocomplete="off" class="layui-input"></td>
							                    	<td><input type="text" value="${list.adjustAmount }" name="batchList[0].adjustAmount" style="border: 0px;" readonly="readonly" class="layui-input"></td>
							                    	<td><input type="text" value="${list.remarks }" name="batchList[0].remarks" maxlength="100" lay-verify="required" autocomplete="off" class="layui-input"></td>
							                    	<td style="width:100px;">
								                    	<button type="button" class="layui-btn layui-btn-sm" id="addBatchBtn${status.count }" onclick="addRow(this);"><i class="layui-icon">&#xe654;</i></button>
											    		<button type="button" class="layui-btn layui-btn-sm" <c:if test="${status.count == 1 && fn:length(budgetBatchVo.budgetBatchLists) == 1}">style="display:none"</c:if> id="delBatchBtn${status.count }" onclick="deleteRow(${status.count })"><i class="layui-icon">&#xe640;</i></button>
											    	</td>
							                    </tr>
							                    </c:forEach>
												<tr>
												    <td class="tg-c" >合计</td>
												    <td></td>
												    <td></td>
													<td><input type="text" id="sumCotAmount" name="sumCotAmount" value="${budgetBatchVo.sumCotAmount}" readonly style="border: 0px;" lay-verify="required|floatNumber" class="layui-input" /></td>
													<td><input type="text" id="sumBudgetAmount" name="sumBudgetAmount" value="${budgetBatchVo.sumBudgetAmount}" readonly style="border: 0px;" lay-verify="required|floatNumber" class="layui-input" /></td>
													<td><input type="text" id="sumAdjustAmount" name="sumAdjustAmount" value="${budgetBatchVo.sumAdjustAmount}" readonly style="border: 0px;" lay-verify="required|floatNumber" class="layui-input" /></td>
													<td></td>
													<td></td>
												</tr>
							                </tbody>
						                </table>
                    				</div>
                    			</div>
                    			<div style="margin-top: 20px;">																
									<div class="layui-form-item">
										<div class="layui-inline">
											<label class="layui-form-label" >概算分劈编制说明</label>
											<div class="layui-input-inline">
												<textarea id="id_writeMemo" placeholder="请输入概算分劈编制说明" name="writeMemo"
												class="layui-textarea" lay-verify="required" maxlength="500"
												style="width: 899px; height: 90px;">${budgetBatchVo.writeMemo }</textarea>
											</div>
										</div>
									</div>
								</div> 
							</fieldset>																																	
							<fieldset class="layui-elem-field layui-field-title fieldset"
								id="baseInfo">
								<legend class="layui-btn layui-legend"
									style="text-align: left; cursor: default;">附件></legend>
								<div style="margin-top: 20px;">
									<div class="layui-form-item">
										<label class="layui-form-label" style="width: 350px;">支持pdf、excel、word、图片资料，可上传多个</label>
									</div>
									<div class="layui-form-item">
										<label class="layui-form-label">概算计算稿</label>
										<div class="layui-input-block">
											<div class="layui-upload">
												<button type="button" class="layui-btn" id="1-upload-more">上传</button>
												<div class="layui-upload-list" id="1-upload-more-list">
												<c:forEach items="${budgetBatchVo.budgetBatchAtts }" var="fileAtt">								              			
						              				<div class="layui-upload-img-div" id="upload_img_${fileAtt.id }">
						              					<c:choose>
							              					<c:when test="${fileAtt.fileSuffix == '.jpg' or fileAtt.fileSuffix == '.jpeg' or fileAtt.fileSuffix == '.png'}">
								              					<img src="${fileHttpPre }/${fileAtt.filePath }" title="${fileAtt.fileName}" class="layui-upload-img">
								              				</c:when>
								              				<c:otherwise>
								              					<img src="${ctx}/resources/images/${fn:substring(fileAtt.fileSuffix,1,5)}.jpg" title="${fileAtt.fileName}" class="layui-upload-img">
								              				</c:otherwise>
						              					</c:choose>
						              					<div class="mask">
						              						<a href="javascript:void(0)" onclick="showImg('${fileHttpPre}/${fileAtt.filePath }');">查看</a>
						              						<a href="javascript:void(0)" onclick="del('${fileAtt.id}')">删除</a>
						              						<input type="hidden" value="1|${fileAtt.fileName}${fileAtt.fileSuffix }||${fileAtt.filePath }" id="fileAtt_${fileAtt.id}" name="fileAtts1" ></input>
						              					</div>
						              					<p>${fileAtt.fileName}</p>
						              				</div>								              			
							              		</c:forEach>
												</div>
											</div>
										</div>
									</div>									
								</div>
							</fieldset>
						</div>
					</div>
				</div>

				<div class="layui-form-item"
					style="position: fixed ! important; right: 30px; bottom: 45%; z-index: 10000;">
					<div class="layui-input-block">
						<button
							class="layui-btn layui-bg-blue layui-btn-normal layui-btn-lg  layui-btn-radius"
							type="button" lay-submit lay-filter="addInfo_form_submit"
							id="addInfo_form_submit">
							<i class="layui-icon layui-icon-ok layuiadmin-button-btn"></i> 提交
						</button>
					</div>
				</div>
			</form>
		</div>
	</div>
</body>
</html>
<script type="text/javascript">	
	String.prototype.format = function () {
		var model = arguments;
	    return this.replace(/\{(\d+)\}/g, function (s, i) { 
	        return model[i];
	    });
	}
	String.prototype.toInt = function () {
		if(this==''){
			return 0;
		}
		return parseInt(this);
	}
	String.prototype.toFloat = function () {
		if(this==''){
			return 0;
		}
		return parseFloat(this);
	}
	Number.prototype.toMoney = function () {
		var m = Math.pow(10, 2);
		return Math.round(this * m) / m;
	}
	var proName;
	var proNameid;
	//静态资源路径前缀
	var staticPath = '${fileHttpPre}';
	var stateJSON = <infopub:dicJson groupNo="A00010028" />;
	layui.config({
	    base: '${ctx}/resources/layuiadmin/' //静态资源所在路径
	  }).extend({
	    index: 'lib/index' //主入口模块
	  }).use(['index', 'set', 'upload', 'element', 'laydate'], function(){
	    var $ = layui.$
	    ,form = layui.form
	    ,element = layui.element
	    ,laydate = layui.laydate
	    ,upload = layui.upload;
		// 正则校验
		form.verify({
			//验证汉字
		    CHS:[
		    	/^[\u0391-\uFFE5]+$/
		    	,'只能输入汉字'
		  	],
		  	//名字校验
		  	COC: [
				/^[\u4e00-\u9fa5_a-zA-Z0-9]+$/
				,'请输入正确的名称'
		  	],
		  	//大于0的正整数
		  	intNumber:[
				/^[1-9]\d*$/
				,'请输入正确的数字'
		  	],
		  	//数字只能有两位小数
		  	floatNumber:[
				/^([-]?)([0-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/
				,'请输入正确的数字'
		  	],
		  	telNumber:[/^[1][3,4,5,7,8,9][0-9]{9}$/
				  		,'请输入正确的号码'
			],
		  	//数字大于0，并只能有两位小数
		  	floatAmount:[
				/^([1-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/
				//var pattern=/^((\d+\.\d*[1-9]\d{1})|(\d*[1-9]\d*\.\d{2}))$/; 
				,'请输入正确的数字'
		  	]
		});
		
		var fileFormat = 'application/zip,application/x-rar-compressed,image/jpeg,image/png,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.presentation,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/pdf';
		//附件格式控制
		uploadRender(1, upload,fileFormat, $);
		
		form.on('select(add_select_proId)', function(data) {
			var id = data.value;
			proNameid = data.value;
			proName = data.elem.getAttribute('proName');
	
			if(id==''||id==null){
				var templateLayuiRowHtml = $('#layui-row').html();
				var $contractList = $('.contract-list');
				$contractList.find(".contract-box").remove();
				$("#add_select_subName").html('');
				$("#id_ImplementingBody").val('');
				$("#id_regionalCompany").val('');
				$("#id_projectLeader").val('');
				$("#id_projectAddress").val('');
				form.render();
	    		layer.msg('请选择项目名称',{icon: 1});    		
	    		return;
	    	}else{
	    		getBudgetBatchByProCode(id); 
	    	}	
		});
		
		form.on('submit(addInfo_form_submit)', function(data) {
			//判断是否上传了概算计算稿
			if ($("input[name=fileAtts1]").length < 1) {
				layer.msg("概算计算稿未上传", {
					icon : 0
				});
				return;
			}
			$("#addInfo_form_submit").removeAttr("lay-submit").removeClass("layui-bg-blue").addClass("layui-btn-disabled");
			//提交 Ajax 成功后，静态更新表格中的数据
               $.ajax({
                   type : 'post',
         		   url : basePath + '/budgetBatch/save',
                   data: $('#addInfo_form').serialize(),
         		   success:function(result){
         				if(result.success){
         					layer.closeAll('loading'); //关闭loading
         					layer.msg('提交单据成功~',{icon: 1});
         					//两秒后关闭当前页面
         					setTimeout(function(){
         						/**
         						 * 查找父菜单，并刷新
         						 */
         						var topDoc = $(window.top.document);
         						var path = basePath + '/budgetBatch/list';
         						// 获取页面名称
         						var name = topDoc.find(".layui-nav-item [lay-href^='" + path + "']").text();
         						if(name == '' || name == null){
         							name = '概算分劈';
         						}
         						window.parent.layui.index.openTabsPage(path, name);
         						var iframe = window.parent.layui.admin.tabsBody(window.parent.layui.admin.tabsPage.index).find(".layadmin-iframe");
         						iframe[0].contentWindow.location.reload(true);
         						
         						/**
         						 * 关闭当前页
         						 */
         						var currPath = basePath + '/budgetBatch/toCopy';
         						var layid = topDoc.find("li[lay-id^='" + currPath + "']").attr('lay-id');
         						window.parent.layui.element.tabDelete('layadmin-layout-tabs', layid);//关闭当前页
         				        }, 2000);
         				}else{
         					layer.closeAll('loading'); //关闭loading
           					$("#addInfo_form_submit").removeClass("layui-btn-disabled").addClass("layui-bg-blue").attr("lay-submit","");
         					layer.msg(result.msg,{icon: 7});
         			  	}
         			}
              });
		});
	});
	
	var uploadRender = function(id, upload, fileFormat,$) {
		upload.render({
			elem : '#' + id + '-upload-more',
			url : basePath + '/budgetBatch/uploadAtt/',
			data : {
				types : id
			},
			multiple : true,
			accept : 'file',
			acceptMime : fileFormat,
			before : function(obj) {
				layer.load();
			},
			done : function(res) {
				if (res.code > 0) {
					layer.closeAll('loading');
					return layer.msg(res.msg, {
						icon : 7
					});
				}
				if (res.entity != null && res.entity.length > 0) {
					for ( var i in res.entity) {
						var budgetBatch = res.entity[i];
						var arr = budgetBatch.split("|");
						var imgSrc = "";
						var suffix = arr[1].substring(arr[1]
								.lastIndexOf(".") + 1, arr[1].length);
						if (suffix == 'jpg' || suffix == 'png') {
							imgSrc = "${fileHttpPre}/" + arr[3];
						} else {
							imgSrc = "${ctx}/resources/images/"
									+ suffix + ".jpg";
						}
						$('#' + id + '-upload-more-list')
								.append(
										'<div class="layui-upload-img-div" id="upload_img_'+arr[2]+'"><img src="'+imgSrc+'" title="'+ arr[1] +'" class="layui-upload-img"><div class="mask"><a href="javascript:void(0)" onclick="showImg(\''
												+ "${fileHttpPre}"
												+ arr[3]
												+ '\');">查看</a><a href="javascript:void(0)" onclick="del(\''
												+ arr[2]
												+ '\')";>删除</a></div><p>'
												+ arr[1]
												+ '</p><input type="hidden" value="'+budgetBatch+'" id="fileAtt_'+arr[2]+'" name="fileAtts'+id+'" ></input></div>');
					}
				}
			},
			allDone : function(obj) {
				layer.closeAll('loading');
			},
			error : function() {
				layer.closeAll('loading');
				layer.msg("上传失败，请稍后再试~", {
					icon : 7
				});
			}
		});
	}
	//删除文件
	function del(index) {
		layui.$("#fileAtt_" + index).remove();
		layui.$("#upload_img_" + index).remove();
	}

	//根据url查看文件
	function showImg(url) {
		var openWin = window.open(url,'','left=410,height=768, width=1024, top=200,  toolbar=no, menubar=no, scrollbars=no, resizable=no,location=no, status=no');
	}
	
	//根据项目名称带出需要的概算分劈字段
	function getBudgetBatchByProCode(id) {		
		var $ = layui.$, form = layui.form
		var proCodeAndCodes = id;
		
		var templateLayuiRowHtml = $('#layui-row').html();
		var $contractList = $('.contract-list');
		$contractList.find(".contract-box").remove();
		
		$.ajax({
			type : "POST", //提交方式  
			url : "${ctx}/budgetBatch/getBudgetBatchByProCode",//路径  
			data : {
				"proCodeAndCodes" : proCodeAndCodes
			},	//数据，这里使用的是Json格式进行传输  
			success : function(result) {	//返回数据根据结果进行相应的处理 
				if (result.flag == true) {
					if(result.budgetBatchProCode!=null){
						$("#id_proCode")
								.attr("value", result.budgetBatchProCode.proCode);//项目编号
						if (result.budgetBatchProCode.orgAreaName != null) {
							$("#id_regionalCompany").attr("value",
									result.budgetBatchProCode.orgAreaName);//区域公司
							$("#areaId").attr("value",
									result.budgetBatchProCode.hrOrgAreaId);//区域公司id
						} else {
							$("#id_regionalCompany").attr("value", "暂时为空不可编辑");//区域公司
						}
						if (result.budgetBatchProCode.hrOrgProId != null) {
							$("#hrOrgProId").attr("value",
									result.budgetBatchProCode.hrOrgProId);//项目公司id	
							$("#id_projectCompany").attr("value",
									result.budgetBatchProCode.orgProName);//项目公司	
						} else {
							$("#id_projectCompany").attr("value", "暂时为空不可编辑");//项目公司
						}
						$("#id_projectAddress").attr("value",
								result.budgetBatchProCode.sgCityName);//项目地址
						$("#sgCityId").attr("value",
								result.budgetBatchProCode.sgCityId);//项目地址城市id		
						$("#id_ImplementingBody").attr("value",
								result.budgetBatchProCode.carryOrg);//实施机构
						$("#id_projectLeader").attr("value",
								result.budgetBatchProCode.proLeader);//项目负责人
								
						//项目名称带出概算清单子项名称集合
						$("#add_select_subName").html('');
						var subList = '<option value>请选择</option>';
						if(result.proContractSubList.length>0){
							for (var i = 0; i <result.proContractSubList.length; i++) {
								subList+= '<option value='+result.proContractSubList[i].subName+'>'+result.proContractSubList[i].subName+'</option>';
							}
					     }
					    $("#add_select_subName").append(subList);	
					    form.render();
					}else{
						$("#id_proCode").attr("value", '');//项目编号
						$("#areaId").attr("value",'');//区域公司id
						$("#id_regionalCompany").attr("value", '');//区域公司
						$("#id_projectCompany").attr("value", '');//项目公司
						$("#hrOrgProId").attr("value",'');//项目公司id
						$("#id_projectAddress").attr("value",'');//项目地址
						$("#sgCityId").attr("value",'');//项目地址城市id		
						$("#id_ImplementingBody").attr("value",'');//实施机构
						$("#id_projectLeader").attr("value",'');//项目负责人	
						$("#add_select_subName").html('');//概算清单子项下拉菜单
					}
					
					if(result.budgetBatchDetailAndSub.length >0 ){
						var hash = {},subList=[];					
						for(var i = 0, j = result.budgetBatchDetailAndSub.length; i < j; i++) {												
							var e = result.budgetBatchDetailAndSub[i];						
							if(typeof(hash[e.contractSubId])=='undefined'){
								hash[e.contractSubId] = subList.length;							
								subList.push({
									subName:e.subName,
									contractSubId:e.contractSubId,
									list:[{
										subRowId : e.orderIdx.indexOf(',')!=-1?e.orderIdx.split(',')[1]:e.orderIdx,
										costType : e.typeName.indexOf(',')!=-1?e.typeName.split(',')[1]:e.typeName,
										projectamountbefore : e.outPreDownAmount,
										outdiscount : e.outPreDownRate,
										inamountAfter : e.outAfterDownAmount
								}]});																						
							}else{								
								var index =  hash[e.contractSubId].toString().toInt();
								subList[index].list.push({
								        subRowId : e.orderIdx.indexOf(',')!=-1?e.orderIdx.split(',')[1]:e.orderIdx,
										costType : e.typeName.indexOf(',')!=-1?e.typeName.split(',')[1]:e.typeName,											
										projectamountbefore : e.outPreDownAmount,
										outdiscount : e.outPreDownRate,
										inamountAfter : e.outAfterDownAmount
								});						
							}						
						}
						
						for (var i = 0, j = subList.length; i < j; i++) {
							var e = result.budgetBatchDetailAndSub[i];						
							var itemNameSub = subList[i].subName,subId = subList[i].contractSubId;
							var tempHtml = templateLayuiRowHtml.format(subId,itemNameSub);
							var $html = $(tempHtml);						
							subList[i].list.forEach(function(e){
								var subRowId = e.subRowId;
								var costType = e.costType;
								var projectamountbefore = e.projectamountbefore;
								var outdiscount = e.outdiscount;
								var inamountAfter = e.inamountAfter;
								
								var trid = subRowId.indexOf('.')!=-1?('tr[id="sub' + subId + 'Row-' + subRowId + '"]'):('tr[id="' + subId + 'Row-' + subRowId + '"]');								
								var $row = $html.find(trid);
								if ($row.length == 1) {
									$row.find('input[type="hidden"]:eq(0)').val(subRowId);
									var $typeNames = $row.find('td:eq(0) input.typeNames');											
									if ($typeNames.val() != costType) {
										$typeNames.val(costType);
									}
									$row.find('td:eq(1) input').val(projectamountbefore);
									$row.find('td:eq(2) input').val(outdiscount);
									$row.find('td:eq(3) input').val(inamountAfter);										
																
								} else {							
									var arr = subRowId.split('.');
									var level = arr.length;
									if (level == 2) {					
										var id = "sub"+subId+"Row-"+subRowId;												
										var types = subRowId.split('.');        
								        var feeTypes = types[0],feeSmallTypes = types[0]+'.'+types[1];								        												
										var pop = arr.pop();
										var parent = subId + 'Row-' + arr[0];												
										var siblings = 'sub' + parent + '.';
										var $parent = $html.find("tr[id='" + parent + "']");
										var $siblings = $html.find("tr[id^='" + siblings + "']");
										var siblingslen = $siblings.length;																					
										
										if (siblingslen > 0) {
											var $last = $($siblings[siblingslen - 1]);
											var lastId = $last.prop('id');
										} else if ($parent.length == 1 && pop == '1') {
										}											
									}
								}						
							});
							
							$contractList.append($html);
						}
					}				
					form.render();
				}
			}
		});
	}
	var rgx = /^([-]?)([0-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/;
	// 校验需要输入数字的input框(请输入正确数字，且保留两位小数！)
	function isNumberAndFloat1(str) {
		var $ = layui.$
		if (str.value == '' || str.value == null) {
			return;
		}		
		var boolrgx = rgx.test(str.value);// true 
		if (boolrgx) {
			return true;
		} else {
			str.value =0;
			layer.msg('请输入正确数字，且保留两位小数！');
		}
	}
	//新增一行概算清单
	function addRow(t){
		var $ = layui.$;
		var delBtnCount = $("button[id^='delBatchBtn']").length;
		if(delBtnCount == 1){
			$("button[id^='delBatchBtn']").each(function(){
				//$(this).removeAttr("style");
			});
		}
		var thisid = $(t).attr("id").substring(11);
		thisid = $("tr[id=batchRow" + thisid + "]").find("td:first").find("input").val();
		thisid = parseInt(thisid);
		var nextIndex = parseInt(thisid) + 1;
		var maxInd = $("tr[id^='batchRow']").length;
		$("tr[id^='batchRow']").each(function(){
			var tId = $(this).attr("id").substring(8);
			tId = parseInt(tId);
		  	if(tId > maxInd){
		  		maxInd = parseInt(tId);
		  	}
		  	var thisIndex = $(this).find("td:first").find("input").val();
		  	thisIndex = parseInt(thisIndex);
		  	var nextId = thisIndex + 1;
		  	if(thisIndex > thisid) {
		  		$("tr[id=batchRow" + tId + "]").find("td:first").find("input").val(nextId);
		  		$(this).find("input").each(function(){
		  			if($(this).attr("name")!=null&&$(this).attr("name")!=''){
		  				var inputName = $(this).attr("name").split(".");
			  			var inpName = "batchList["+thisIndex+"].";
			  			$(this).attr("name",inpName+inputName[1]);
		  			}		  			
		  		});
		  		$(this).find("select").each(function () {
		            var name = $(this).attr('name');
		            $(this).attr('name', name.replace(/\d+/g, thisIndex));            
		        })
		  	}
		});
		var ind = maxInd + 1;
		var add_select_subName = $("#select_subname").clone();
		var medalHtml = '';
		medalHtml += '<tr id="batchRow'+ind+'">';
		medalHtml += '	<td class="tg-c"><input type="text" name="batchList['+thisid+'].showIdx" value="'+nextIndex+'" style="border: 0px;width:50px" readonly="readonly" class="layui-input"></td>';
		medalHtml += '	<td>'+add_select_subName.html()+'</td>';
		medalHtml += '	<td><input type="text" name="batchList['+thisid+'].subDivideName" maxlength="50" lay-verify="required" autocomplete="off" class="layui-input"></td>';
		medalHtml += '	<td><input type="text" name="batchList['+thisid+'].cotAmount" maxlength="13" onblur="calcSumAmount(this);arabiaToCN(this,1);" lay-verify="required|floatNumber" autocomplete="off" class="layui-input"></td>';
		medalHtml += '	<td><input type="text" name="batchList['+thisid+'].budgetAmount" maxlength="13" onblur="calcSumAmount(this);arabiaToCN(this,1);" lay-verify="required|floatAmount"  autocomplete="off" class="layui-input"></td>';
		medalHtml += '	<td><input type="text" name="batchList['+thisid+'].adjustAmount" style="border: 0px;" readonly="readonly" class="layui-input"></td>';
		medalHtml += '	<td><input type="text" name="batchList['+thisid+'].remarks" maxlength="50" lay-verify="required" autocomplete="off" class="layui-input"></td>';
		medalHtml += '	<td>';
		medalHtml += '		<button type="button" class="layui-btn layui-btn-sm" id="addBatchBtn'+ind+'" onclick="addRow(this);"><i class="layui-icon">&#xe654;</i></button>';
		medalHtml += '		<button type="button" class="layui-btn layui-btn-sm" id="delBatchBtn'+ind+'" onclick="deleteRow('+ind+')"><i class="layui-icon">&#xe640;</i></button>';
		medalHtml += '	</td>';
		medalHtml += '</tr>';
		

		var $medalHtml=$(medalHtml)
		$medalHtml.find("select").each(function () {
			var id = $(this).attr('id');
            var name = $(this).attr('name');
            $(this).attr('id', id+ thisid);
            $(this).attr('name', name.replace(/\d+/g, thisid));            
        })
        
		
		$(t).parent().parent().after($medalHtml);
		layui.form.render();
	}
	
	//删除一行概算清单
	function deleteRow(id){
		var $ = layui.$;
		layui.layer.confirm('确定删除？',{icon:3, title :'提示'}, function(index){
		   	var thisid = $("tr[id=batchRow" + id + "]").find("td:first").find("input").val();
	    	thisid = parseInt(thisid);
	    	$("tr[id^='batchRow']").each(function(){
				var tId = $(this).attr("id").substring(8);
				tId = parseInt(tId);
			  	var thisIndex = $("tr[id=batchRow" + tId + "]").find("td:first").find("input").val();
			  	thisIndex = parseInt(thisIndex);
			  	var nextId = thisIndex - 1;
			  	if(thisIndex > thisid) {
			  		$("tr[id=batchRow" + tId + "]").find("td:first").find("input").val(nextId);
			  		$(this).find("input").each(function(){
			  			if($(this).attr("name")!=null&&$(this).attr("name")!=''){
			  				var inputName = $(this).attr("name").split(".");
				  			var inpName = "batchList["+(nextId-1)+"].";
				  			$(this).attr("name",inpName+inputName[1]);
			  			}				  			
			  		});
					$(this).find("select").each(function () {
			            var name = $(this).attr('name');
			            $(this).attr('name', name.replace(/\d+/g, (nextId-1)));
			        })
			  	}
			});
	    	
	    	//删除行的合同金额,概算金额和增减金额
	    	var strCotAmount = $("tr[id='batchRow" + id + "']")
	    		.find("input[name='"+name.split('.')[0]+".cotAmount']").val();
	    	if(strCotAmount==''||strCotAmount==null){
	    		strCotAmount = 0;
	    	}else{
	    		strCotAmount = parseFloat(strCotAmount);
	    	}	    	
			var strBudgetAmount = $("tr[id=batchRow" + id + "]")
				.find("input[name='"+name.split('.')[0]+".budgetAmount']").val();
			if(strBudgetAmount==''||strBudgetAmount==null){
				strBudgetAmount = 0;
	    	}else{
	    		strBudgetAmount = parseFloat(strBudgetAmount);
	    	}			
			var strAdjustAmount = $("tr[id=batchRow" + id + "]")
				.find("input[name='"+name.split('.')[0]+".adjustAmount']").val();
			if(strAdjustAmount==''||strAdjustAmount==null){
				strAdjustAmount = 0;
	    	}else{
	    		strAdjustAmount = parseFloat(strAdjustAmount);
	    	}	
						
			//减行时重新计算合同金额
			var cotAmountStr = $('#sumCotAmount').val();
			if(cotAmountStr==''||cotAmountStr==null){
				cotAmountStr = 0;
	    	}else{
	    		cotAmountStr = parseFloat(cotAmountStr);
	    	}
			var cotAmountNewStr = cotAmountStr - strCotAmount;
			$('#sumCotAmount').val(cotAmountNewStr.toMoney());
			
			//减行时重新计算概算金额
			var budgetAmountStr = $('#sumBudgetAmount').val();
			if(budgetAmountStr==''||budgetAmountStr==null){
				budgetAmountStr = 0;
	    	}else{
	    		budgetAmountStr = parseFloat(budgetAmountStr);
	    	}
			var budgetAmountNewStr = budgetAmountStr - strBudgetAmount;
			$('#sumBudgetAmount').val(budgetAmountNewStr.toMoney());
			
			//减行时重新计算增减金额
			var adjustAmountStr = $('#sumAdjustAmount').val();
			if(adjustAmountStr==''||adjustAmountStr==null){
				adjustAmountStr = 0;
	    	}else{
	    		adjustAmountStr = parseFloat(adjustAmountStr);
	    	}
			var adjustAmountNewStr = adjustAmountStr - strAdjustAmount;
			$('#sumAdjustAmount').val(adjustAmountNewStr.toMoney());
	    		    	
	    	$("#batchRow"+id).remove();
	    	var delBtnCount = $("button[id^='delBatchBtn']").length;
			if(delBtnCount == 1){
				$("button[id^='delBatchBtn']").each(function(){
					$(this).attr("style","display:none");
				});
			}
			layui.layer.close(index);
		});
	}
	//计算合同金额合计,概算金额合计以及增减金额合计
	function calcSumAmount(obj){
		var $ = layui.$;
		if (obj.value == '' || obj.value == null) {
			return;
		}
		var rgx = /^([-]?)([0-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/;
		var boolrgx = rgx.test(obj.value);// true
		if(isNaN(obj.value)||!boolrgx){
			obj.value=0;
			var name = $(obj).attr("name");
			var sumAdjustAmount = 0;
			if(name.split('.')[1] == 'cotAmount'){//合同金额input框
  				var adjustAmount =0;
  				var sumCotAmount = 0;
  				var budgetAmount = $("input[name='"+name.split('.')[0]+".budgetAmount']").val();
  				if(budgetAmount == ''){
  					$("input[name$=cotAmount]").each(function(){//计算合同金额总计
  	  	  				var tId = $(this).val();
  	  	  				if(tId != ''){
  	  	  					sumCotAmount = sumCotAmount + parseFloat(tId);
  	  	  				}
  	  	  			});
  	  				$("#sumCotAmount").val(sumCotAmount.toFixed(2));
  					return;
  				}else{
  					adjustAmount = parseFloat(budgetAmount) - parseFloat(obj.value);
  					$("input[name='"+name.split('.')[0]+".adjustAmount']").val(adjustAmount.toFixed(2));
  					$("input[name$=cotAmount]").each(function(){//计算合同金额总计
  	  	  				var tId = $(this).val();
  	  	  				if(tId != ''){
  	  	  					sumCotAmount = sumCotAmount + parseFloat(tId);
  	  	  				}
  	  	  			});
  	  				$("#sumCotAmount").val(sumCotAmount.toFixed(2));
  				}			
  				
  			}else if(name.split('.')[1] == 'budgetAmount'){//概算金额input框
  				var adjustAmount =0;
  				var sumBudgetAmount = 0;
  				var cotAmount = $("input[name='"+name.split('.')[0]+".cotAmount']").val();
  				if(cotAmount == ''){
  					$("input[name$=budgetAmount]").each(function(){//计算概算金额总计
  	  	  				var tId = $(this).val();
  	  	  				if(tId != ''){
  	  	  					sumBudgetAmount = sumBudgetAmount + parseFloat(tId);
  	  	  				}
  	  	  			});
  	  				$("#sumBudgetAmount").val(sumBudgetAmount.toFixed(2));
  					return;
  				}else{
  					adjustAmount = parseFloat(obj.value) - parseFloat(cotAmount);
  					$("input[name='"+name.split('.')[0]+".adjustAmount']").val(adjustAmount.toFixed(2));
  					$("input[name$=budgetAmount]").each(function(){//计算概算金额总计
  	  	  				var tId = $(this).val();
  	  	  				if(tId != ''){
  	  	  					sumBudgetAmount = sumBudgetAmount + parseFloat(tId);
  	  	  				}
  	  	  			});
  	  				$("#sumBudgetAmount").val(sumBudgetAmount.toFixed(2));
  				}  				
  			} 
			$("input[name$=adjustAmount]").each(function(){//计算增减金额总计
  				var tId = $(this).val();
  				if(tId != ''){
  					sumAdjustAmount = sumAdjustAmount + parseFloat(tId);
  				}
  			});
			$("#sumAdjustAmount").val(sumAdjustAmount.toFixed(2));
			layer.msg('请输入正确数字，且保留两位小数！');
  		}else{
  			var name = $(obj).attr("name");
  			var sumAdjustAmount = 0;
  			if(name.split('.')[1] == 'cotAmount'){//合同金额input框
  				var adjustAmount =0;
  				var sumCotAmount = 0;
  				var budgetAmount = $("input[name='"+name.split('.')[0]+".budgetAmount']").val();
  				if(budgetAmount == ''){
  					$("input[name$=cotAmount]").each(function(){//计算合同金额总计
  	  	  				var tId = $(this).val();
  	  	  				if(tId != ''){
  	  	  					sumCotAmount = sumCotAmount + parseFloat(tId);
  	  	  				}
  	  	  			});
  	  				$("#sumCotAmount").val(sumCotAmount.toFixed(2));
  					return;
  				}else{
  					adjustAmount = parseFloat(budgetAmount) - parseFloat(obj.value);
  					$("input[name='"+name.split('.')[0]+".adjustAmount']").val(adjustAmount.toFixed(2));
  					$("input[name$=cotAmount]").each(function(){//计算合同金额总计
  	  	  				var tId = $(this).val();
  	  	  				if(tId != ''){
  	  	  					sumCotAmount = sumCotAmount + parseFloat(tId);
  	  	  				}
  	  	  			});
  	  				$("#sumCotAmount").val(sumCotAmount.toFixed(2));
  				}			
  				
  			}else if(name.split('.')[1] == 'budgetAmount'){//概算金额input框
  				var adjustAmount =0;
  				var sumBudgetAmount = 0;
  				var cotAmount = $("input[name='"+name.split('.')[0]+".cotAmount']").val();
  				if(cotAmount == ''){
  					$("input[name$=budgetAmount]").each(function(){//计算概算金额总计
  	  	  				var tId = $(this).val();
  	  	  				if(tId != ''){
  	  	  					sumBudgetAmount = sumBudgetAmount + parseFloat(tId);
  	  	  				}
  	  	  			});
  	  				$("#sumBudgetAmount").val(sumBudgetAmount.toFixed(2));
  					return;
  				}else{
  					adjustAmount = parseFloat(obj.value) - parseFloat(cotAmount);
  					$("input[name='"+name.split('.')[0]+".adjustAmount']").val(adjustAmount.toFixed(2));
  					$("input[name$=budgetAmount]").each(function(){//计算概算金额总计
  	  	  				var tId = $(this).val();
  	  	  				if(tId != ''){
  	  	  					sumBudgetAmount = sumBudgetAmount + parseFloat(tId);
  	  	  				}
  	  	  			});
  	  				$("#sumBudgetAmount").val(sumBudgetAmount.toFixed(2));
  				}  				
  			}  			
  	  		$("input[name$=adjustAmount]").each(function(){//计算增减金额总计
  				var tId = $(this).val();
  				if(tId != ''){
  					sumAdjustAmount = sumAdjustAmount + parseFloat(tId);
  				}
  			});
  	  		$("#sumAdjustAmount").val(sumAdjustAmount.toFixed(2));
  		}	
	}
</script>